#include "stdafx.h"
#include "HtmlEditCtrlEx.h"
// CHtmlEditCtrlEx


BEGIN_MESSAGE_MAP(CHtmlEditCtrlEx, CHtmlEditCtrl)
END_MESSAGE_MAP()

BOOL CHtmlEditCtrlEx::CreateFromStatic( UINT nID, CWnd* pParent )
{
	CStatic wndStatic;
	if ( !wndStatic.SubclassDlgItem(nID, pParent))
	{
		return( FALSE );
	}
	CRect rc;
	wndStatic.GetWindowRect( &rc );
	pParent->ScreenToClient( &rc );
	return Create( 0, (WS_CHILD | WS_VISIBLE), rc, pParent, nID, 0 );
};

BOOL CHtmlEditCtrlEx::PreTranslateMessage(MSG* pMsg)
{
	if( !m_fEnableContextMenu )
	{
		switch (pMsg->message)
		{
		case WM_CONTEXTMENU:
		case WM_RBUTTONUP:
		case WM_RBUTTONDOWN:
		case WM_RBUTTONDBLCLK:
			if (pMsg->message==WM_RBUTTONUP)
			{
				// let parent handle context menu
				GetParent()->SendMessage(WM_CONTEXTMENU, pMsg->wParam, pMsg->lParam);
			}
			return TRUE; // eat it
		}
	}

	// 1169d TRACE("HTML EDIT MSG: %ud\n", pMsg->message);

	return CHtmlEditCtrl::PreTranslateMessage(pMsg);
}


HRESULT CHtmlEditCtrlEx::SetDocumentTitle( CString szTitle )
{
	HRESULT hr = E_FAIL;
	CComBSTR bstrTitle( szTitle );

	// set document
	CComPtr<IHTMLDocument2> document;
	GetDocument( &document );
	if( document )
		hr = document->put_title( bstrTitle );
	return hr;
}


// overide to discard BOM
HRESULT CHtmlEditCtrlEx::GetDocumentHTML( CString& sHtml )
{
	HRESULT hr = CHtmlEditCtrl::GetDocumentHTML( sHtml );
	if( sHtml[0] != '<' )
	{
		sHtml = sHtml.Mid(3);
	}

	return hr;
}


HRESULT CHtmlEditCtrlEx::SetDocumentHTML( CString& sHtml )
{
	HRESULT hr;
	int nOffset=0;
	if( sHtml[0]==0xef && sHtml[1]==0xbb && sHtml[2]==0xbf )
	{ // BOM may be there
		nOffset = 3;
	}

	hr = CHtmlEditCtrl::SetDocumentHTML( sHtml );
	return hr;
}


HRESULT CHtmlEditCtrlEx::SetDocumentHTML( CString& sHtml, BOOL bWait )
{
	HRESULT hr;
	int nOffset=0;
	if( sHtml[0]==0xef && sHtml[1]==0xbb && sHtml[2]==0xbf )
	{ // BOM may be there
		nOffset = 3;
	}

	hr = CHtmlEditCtrl::SetDocumentHTML( sHtml );

	// check for wait
	if( bWait )
	{
		// get document
		CComPtr<IHTMLDocument2> document;
		GetDocument( &document );

		BSTR ready;
		document->get_readyState( &ready );
		while( wcscmp(ready, L"complete") )
		{
			AfxPumpMessage();
			document->get_readyState( &ready );
		};
	}

	return hr;
}


HRESULT CHtmlEditCtrlEx::WaitForComplete()
{
	HRESULT hr = E_FAIL;
	// get document
	CComPtr<IHTMLDocument2> document;
	GetDocument( &document );
	if( !document )
		return hr;

	BSTR ready;
	document->get_readyState( &ready );
	while( wcscmp(ready, L"complete") )
	{
		AfxPumpMessage();
		hr = document->get_readyState( &ready );
	};

	return hr;
}